package com.link4a.doms.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.link4a.doms.Constants;
import com.link4a.doms.exception.BusinessException;
import com.link4a.doms.exception.ValidationException;
import com.link4a.doms.model.Provider;
import com.link4a.doms.service.ProviderService;
import com.link4a.doms.vo.ProviderCondition;
import com.link4a.doms.web.ControllerSupport;
import com.link4a.doms.web.JsonResult;
import com.link4a.doms.web.auth.Privilege;

@Controller
@RequestMapping("provider")
public class ProviderController extends ControllerSupport{
	
	@Autowired
	private ProviderService providerService;
	
	@RequestMapping
	@ResponseBody
	public JsonResult findPage(@RequestBody ProviderCondition condition){
		return success(providerService.findPage(condition));
	}
	
	@RequestMapping
	@ResponseBody
	public JsonResult list(@RequestParam(value="searchstr") String keyword){
		return success(providerService.listByKeyword(keyword));
	}
	
	@RequestMapping(value="/delete/{id}", method=RequestMethod.POST)
	@ResponseBody
	@Privilege(Constants.PROVIDER_CUD)
	public JsonResult delete(@PathVariable int id){
		try {
			providerService.delete(id);
			return success();
		} catch (BusinessException e) {
			return fail(e.getMessage());
		}
	}
	
	@RequestMapping(method=RequestMethod.POST)
	@ResponseBody
	@Privilege(Constants.PROVIDER_CUD)
	public JsonResult create(@RequestBody Provider provider) throws BusinessException{
		try {
			providerService.create(provider);
			return success();
		} catch (ValidationException e) {
			return result(e.getCode());
		}
	}
	
	@RequestMapping(method=RequestMethod.POST)
	@ResponseBody
	@Privilege(Constants.PROVIDER_CUD)
	public JsonResult update(@RequestBody Provider provider){
		try {
			providerService.update(provider);
			return success();
		} catch (ValidationException e) {
			return result(e.getCode());
		}
	}
	
	@RequestMapping
	@Privilege(Constants.PROVIDER_INDEX)
	public ModelAndView index(){
		ModelAndView mav = new ModelAndView("/business/provider");
		return mav;
	}
}
